<template>
  <view>
    <view class="exam-card" :class="[showPanel === undefined ? '' : showPanel ? 'slide-up' : 'slide-down']">
      <!-- 头部 -->
      <view class="card-header">

        <!-- 收藏 -->
        <view class="fav" @click="onFav">
          <text v-if="isFav" class="iconfont icon-fav-fill warning-color"></text>
          <text v-else class="iconfont icon-fav"></text>
          <text style="margin-left: 12rpx">收藏</text>
        </view>
        <!-- 对错情况 - 只有刷题模式和答题模式交卷后显示 -->
        <view class="score" v-if="examType == config.examTypeDict[1] || isCompleted">
          <text class="iconfont icon-correct primary-color"></text>
          <text class="primary-color" style="margin: 0 12rpx">{{ correctNum }}</text>
          <text class="iconfont icon-wrong error-color" style="margin-left: 12rpx"></text>
          <text class="error-color" style="margin: 0 12rpx">{{ wrongNum }}</text>
        </view>
        <!-- 模拟考试倒计时 -->
        <view v-else-if="examType == config.examTypeDict[2] && !isCompleted">
          <uni-countdown :show-day="false" :minute="config.countdown" @timeup="timeup"></uni-countdown>
        </view>
        <!-- 答题卡面板 -->
        <view class="statistics" @click="openPanel">
          <text class="iconfont icon-grid success-color"></text>
          <text decode class="success-color" style="margin-left: 12rpx">
            {{ examIndex + 1 }} / {{ total || '--' }}
          </text>
        </view>
      </view>
      <!-- 面板 -->
      <view class="card-panel" v-if="showPanel">
        <scroll-view scroll-y class="panel-scroll">
          <view class="panel-content">
            <view class="topic" v-for="(item, index) in examData" :key="item.questionId"
              @click="skipTopic(item, index)">
              <view class="topic-item" :class="{
                'active' :item.index == paper.data,
                disabled: !item.submitted && !item.selected
              }">
                <text>{{ index + 1 }}</text>
              </view>
              <view class="icon-bg iconfont" :class="[topicMark(item)]"></view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 遮罩层 -->
    <view class="mask" v-if="showPanel" @click="closePanel"></view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
  import config from '@/uni_modules/sv-exam-plus/config.js'
  import store from '@/uni_modules/sv-exam-plus/store/index.js'
  import {
    collectAPI,
    deleteCollectAPI
  } from '@/api/addPaper/addpaper.js'
  export default {
    props: {
      // 当前题目
      paper: {
        type: Object,
        default: () => {}
      },
    },
    data() {
      return {
        config, // 兼容写法，需要先声明否则报错
        isFav: false,
        showPanel: undefined, // 默认undefined取消初始动画
        throttleNow: 0,
        isCompleted: false,
        questionId: ''
      }
    },
    // #ifdef VUE2
    model: {
      prop: 'paper',
      event: 'update:paper'
    },
    // #endif
    computed: {
      examData: {
        set(newData) {
          store.commit('updateData', newData)
        },
        get() {
          return store.state.examData
        }
      },
      examType: {
        set(newType) {
          store.commit('updateType', newType)
        },
        get() {
          return store.state.examType
        }
      },
      examFavs: {
        set(newFavs) {
          store.commit('updateFavs', newFavs)
        },
        get() {
          return store.state.examFavs
        }
      },
      examIndex: {
        set(newIndex) {
          store.commit('updateIndex', newIndex)
        },
        get() {
          return store.state.examIndex===-1 ? 0 :store.state.examIndex
        }
      },
      total() {
        return store.state.examData.length
      },
      correctNum() {
        return store.state.correctNum
      },
      wrongNum() {
        return store.state.wrongNum
      },
      examPaperId() {
        return store.state.examPaperId
      }
    },
    watch: {
      paper: {
        handler() {
          // 判断是否已收藏
          this.isFav = this.examFavs?.some((item) => item.questionId === this.paper.data?.questionId)
        },
        immediate: true
      },
      examFavs: {
        handler() {
          // 判断是否已收藏
          this.isFav = this.examFavs?.some((item) => item.questionId === this.paper.data?.questionId)
        },
        immediate: true
      }

    },
    created() {
      this.init()
      this.onSubmited()
    },
    // #ifdef VUE2
    beforeDestroy() {
      // 移除事件监听
      uni.$off('e-exam-paper-item-submit')
      uni.$off('e-exam-paper-complete')
      uni.$off('e-exam-paper-item-fav')
    },
    // #endif
    // #ifdef VUE3
    beforeUnmount() {
      // 移除事件监听
      uni.$off('e-exam-paper-item-submit')
      uni.$off('e-exam-paper-complete')
      uni.$off('e-exam-paper-item-fav')
    },
    // #endif
    methods: {
      init() {


      },
      async onFav() {
        if (Date.now() - this.throttleNow < this.config.favThrottle) {
          uni.showToast({
            title: this.config.favThrottleText,
            icon: 'none'
          })
          return
        }
        // 节流标志更新赋值
        // this.throttleNow = Date.now()
        if (!this.isFav) {
          const param = {
            examPaperId: this.examPaperId,
            questionId: this.paper.data.questionId
          }
          await collectAPI(param).then((res) => {
            this.$refs.uToast.show({
              title: '收藏成功',
              type: 'warning',
              icon: false
            })
            store.commit('updateFavs', this.paper.data)
            this.isFav = true
          })
        } else if (this.isFav) {
          const param = {
            examPaperId: this.examPaperId,
            questionId: this.paper.data.questionId || ''
          }
          await deleteCollectAPI(param).then((res) => {
            this.$refs.uToast.show({
              title: '取消收藏成功',
              type: 'warning',
              icon: false
            })
            this.isFav = false
          })
        }



        uni.$emit('e-exam-paper-item-fav', {
          paper: this.paper,
          isfav: this.isFav
        })
      },
      openPanel() {
        this.showPanel = !this.showPanel
      },
      closePanel() {
        this.showPanel = false
      },
      skipTopic(data, index) {
        this.$emit('update:paper', {
          data,
          index
        })
        // 关闭面板
        this.closePanel()
      },
      /**
       * 做题标记
       * @param {Object} item 当前题目情况
       * 规则:
       * 1. 未做: 空
       * 2. 已做未提交: 已做标记
       * 2. 已提交做错: 错误标记
       * 3. 已提交做对: 正确标记
       */
      topicMark(item) {
        if (item.submitted) {
          // 已提交
          if (item.correct) {
            // 做对
            return 'icon-correct primary-color'
          } else {
            // 做错
            return 'icon-wrong error-color'
          }
        } else {
          // 未提交
          if (item.selected && item.selected.length > 0) {
            // 已做
            return 'icon-select success-color'
          } else {
            // 未做
            return ''
          }
        }
      },
      // 监听提交/交卷
      onSubmited() {
        // 单个题目提交
        uni.$on('e-exam-paper-item-submit', (e) => {
          const temp = this.examData
          temp[e.index] = Object.assign({
            ...temp[e.index]
          }, {
            correct: e.correct,
            selected: e.selected
          })
          store.commit('updateData', temp)
          // 批改对错情况
          store.commit('updateNum')
        })
        // 整张试卷交卷
        uni.$on('e-exam-paper-complete', () => {
          this.isCompleted = true
        })
      },
      timeup() {
        uni.showModal({
          title: '系统提示',
          content: '考试时间结束，请交卷',
          showCancel: false,
          success: ({
            confirm
          }) => {
            if (confirm) {
              uni.$emit('e-exam-paper-complete', this.examData)
            }
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  @import '@/uni_modules/sv-exam-plus/icons/iconfont.css';

  .exam-card {
    width: 100%;
    height: var(--card-height);
    border-top: 1px solid #{var(--border-color)};
    position: fixed;
    bottom: calc(#{var(--card-header-height) - var(--card-height)});
    z-index: 9;
    background-color: var(--bg-color);
    box-sizing: border-box;

    .card-header {
      height: var(--card-header-height);
      padding: 0 #{var(--paper-unit-12)};
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .fav {
        cursor: pointer;
      }

      .score {}

      .statistics {
        cursor: pointer;
      }
    }

    .card-panel {
      height: calc(100% - #{var(--card-header-height)});
      box-sizing: border-box;
      border-top: 1px solid #{var(--border-color)};

      .panel-scroll {
        height: 100%;
      }

      .panel-content {
        display: grid;
        grid-template-columns: repeat(6, 1fr);
        grid-gap: var(--paper-unit-12);
        padding: var(--paper-unit-12);

        .topic {
          width: 100%;
          height: 45px;
          display: flex;
          justify-content: center;
          align-items: center;
          position: relative;

          .topic-item {
            width: 40px;
            height: 40px;
            border: 1px solid #{var(--border-color)};
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
            font-weight: 700;

            &.active {
              border: 1px solid #{var(--border-highlight-color)};
            }
          }

          .icon-bg {
            width: 40px;
            height: 40px;
            font-size: 40px;
            opacity: 0.4;
            position: absolute;
            top: 50%;
            left: 50%;
            right: 0;
            bottom: 0;
            transform: translate(-50%, -50%);
            z-index: -1;
          }
        }
      }
    }
  }

  .mask {
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    z-index: 1;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .primary-color {
    color: var(--primary-color);
  }

  .success-color {
    color: var(--success-color);
  }

  .warning-color {
    color: var(--warning-color);
  }

  .error-color {
    color: var(--error-color);
  }

  .info-color {
    color: var(--info-color);
  }

  .slide-up {
    animation: slide-up 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
  }

  .slide-down {
    animation: slide-down 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
  }
  .disabled {
    background: #eee;
  }

  @keyframes slide-up {
    0% {
      transform: translateY(0);
    }

    100% {
      transform: translateY(calc(#{var(--card-header-height)} - 100%));
    }
  }

  @keyframes slide-down {
    0% {
      transform: translateY(calc(#{var(--card-header-height)} - 100%));
    }

    100% {
      transform: translateY(0);
    }
  }
</style>